package com.javaweb.newfilter;

import com.javaweb.common.DispatcherTool;
import com.javaweb.common.NullableTool;
import com.javaweb.newservlelt.LoginServlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebFilter(filterName = "FilterAuth",
            urlPatterns = {"/*"}
)
public class FilterAuth implements Filter {
    private List<String> EXLUSIVE_URL_LIST = List.of(
            "/static/", "/css/", "/js/",
            "login.jsp","index.jsp","/adminx/","/beforeClass/","/rating","/test","/ajax",
            "register.jsp",
            "message.jsp", "login", "register"
    ) ;
    @Override
    public void destroy() {
    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req ;
        String url = request.getRequestURI() ;
        System.out.println("[INFO] FilterAuth got a URL: " + url ) ;
        if ( ! isExculsive(url)) {
            if ( ! isLogin(request)) {
                System.out.println("[INFO] the url was BLOCKED for : " + url ) ;
                DispatcherTool.indirectForwardToClient(request,
                                                      (HttpServletResponse)resp,
                                                        "02/servlet/login.jsp",
                                                         "未登录用户！");
                return ;
            }
        }
        System.out.println("[INFO] the url was PASSED for : " + url ) ;
        chain.doFilter(req, resp);
    }
    @Override
    public void init(FilterConfig config) throws ServletException {

    }

    private boolean isExculsive(String url) {
        for (String exUrl : EXLUSIVE_URL_LIST) {
            if (url.contains(exUrl)) {
                return true ;
            }
        }
        return false ;

    }

    private boolean isLogin(HttpServletRequest req) {
        return ! NullableTool.isNull(req.getSession()
                                .getAttribute(LoginServlet.UER_ATTR)) ;

    }

}
